module one {
	export class DynamicMovieClip extends egret.DisplayObjectContainer {

		static LOAD_COMPLETE: string = "onLoadComplete";
		static LOOP_COMPLETE: string = "onLoopComplete";

		private key: string;
		public constructor(key: string, movieClipName?: string) {
			super();

			this.change(key, movieClipName);
			this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddTo, this);
			this.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.onRmoveFrom, this);
		}

		public change(key: string, movieClipName?: string): void {
			this.key = key;

			this.destroy();

			this.count++;
			this.load(key, movieClipName, this.count);
		}

		private count:number = 0;
		private load(key: string, movieClipName: string, count:number): void {
			let pngJsonLoaded: boolean = false;
			let pngLoaded: boolean = false;
			RES.getResAsync(key + "_json", () => {
				if (pngLoaded) {
					this.createMovie(key, movieClipName, count);
				}
				pngJsonLoaded = true;
			}, this);
			RES.getResAsync(key + "_png", () => {
				if (pngJsonLoaded) {
					this.createMovie(key, movieClipName, count);
				}
				pngLoaded = true;
			}, this);
		}

		private mc:egret.MovieClip;
		private createMovie(key: string, movieClipName: string, count:number): void {
			if (this.count != count) {
				return;
			}

			//创建动画工厂
			var mcDataFactory:egret.MovieClipDataFactory = new egret.MovieClipDataFactory(RES.getRes(key + "_json"), RES.getRes(key + "_png"));
			//创建 MovieClip，将工厂生成的 MovieClipData 传入参数
			var mc:egret.MovieClip = this.mc = new egret.MovieClip(mcDataFactory.generateMovieClipData(movieClipName));
			this.addChild(mc);

			//播放攻击动画
			if (this.frame) {
				this.mc.gotoAndPlay(this.frame, this.playTimes);
			}

			this.addListeners();

			this.dispatchEventWith(DynamicMovieClip.LOAD_COMPLETE);
		}

		private onAddTo(e: egret.Event): void {
			this.addListeners();
		}

		private onRmoveFrom(e: egret.Event): void {
			if (e.currentTarget == e.target) {
				this.destroy();
			}
		}

		private addListeners(): void {
			if (this.mc) {
				//添加播放完成事件
				// this.mc.addEventListener(egret.Event.COMPLETE, this.onListener, this);
				//添加循环播放完成事件
				this.mc.addEventListener(egret.Event.LOOP_COMPLETE, this.onListener, this);
			}
		}

		private onListener(e: egret.Event): void {
			this.dispatchEventWith(DynamicMovieClip.LOOP_COMPLETE);
		}

		public destroy(): void {
			if (this.mc) {
				this.mc.removeEventListener(egret.Event.LOOP_COMPLETE, this.onListener, this);
			}
		}

		private frame: string;
		private playTimes: number;
		public play(frame: string, playTimes: number): void {
			this.frame = frame;
			this.playTimes = playTimes;

			if (this.mc) {
				this.mc.gotoAndPlay(this.frame, this.playTimes);
			}
		}

		public stop(): void {
			if (this.mc) {
				this.mc.stop();
			}
		}

		private timescale: number = 1;
		public setScale(scale: number): void {
			this.timescale = scale;

			if (this.mc) {
				this.mc.frameRate = 24 * scale;
			}
		}
	}
}